<template>
  <div>

    <!--查询条件-->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="统计编码">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入统计编码"
          clearable
          style="width: 240px"
          @keyup.enter.native="getListByPage()"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getListByPage()">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetData()">重置</el-button>
      </el-form-item>
    </el-form>

    <!--操作按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="batchDeleteStatistics()"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="showAdd()"
        >新增</el-button>
      </el-col>
    </el-row>

    <!--表格开始-->
    <el-table
      v-loading="loading"
      :data="dataList"
      :header-cell-style="{background:'#F8F8F9'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        type="index"
        label="序号"
        width="50"
      />
      <el-table-column label="统计编码" align="center" prop="code" />
      <el-table-column label="统计类型" align="center" prop="dataType">
        <template slot-scope="scope">
          <span v-if="scope.row.dataType === 1">温度</span>
          <span v-if="scope.row.dataType === 2">湿度</span>
          <span v-if="scope.row.dataType === 3">光照强度</span>
          <span v-if="scope.row.dataType === 4">二氧化碳浓度</span>
        </template>
      </el-table-column>
      <el-table-column label="最大值" align="center" prop="max" />
      <el-table-column label="最小值" align="center" prop="min" />
      <el-table-column label="平均数" align="center" prop="average" />
      <el-table-column label="总共数量" align="center" prop="total" />
      <el-table-column label="正常数量" align="center" prop="normal" />
      <el-table-column label="异常数量" align="center" prop="exception" />
      <el-table-column label="统计开始时间" align="center" prop="countBeginDate" />
      <el-table-column label="统计结束时间" align="center" prop="countEndDate" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
    </el-table>
    <!--表格开始-->

    <!-- 分页组件 -->
    <el-pagination
      v-if="total > 0"
      :total="total"
      :current-page.sync="queryParams.current"
      :page-size.sync="queryParams.pageSize"
      :page-sizes="[1,2, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      style="padding: 30px 0; text-align: center;"
      @current-change="getListByPage(queryParams.current)"
      @size-change="handleSizeChange"
    />

    <!-- 弹出框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="75%">
      <!--查询条件-->
      <el-form ref="queryForm" :model="statistics" size="small" :inline="true">
        <el-form-item label="统计类型">
          <el-select
            v-model="statistics.dataType"
            placeholder="请选择统计类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in dataTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收集时间">
          <el-date-picker
            v-model="rangeTime"
            style="width: 360px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getStatisticsData()">开始统计</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="addDataList"
        :header-cell-style="{background:'#F8F8F9'}"
      >
        <el-table-column label="统计类型" align="center" prop="dataType">
          <template slot-scope="scope">
            <span v-if="scope.row.dataType === 1">温度</span>
            <span v-if="scope.row.dataType === 2">湿度</span>
            <span v-if="scope.row.dataType === 3">光照强度</span>
            <span v-if="scope.row.dataType === 3">二氧化碳浓度</span>
          </template>
        </el-table-column>
        <el-table-column label="最大值" align="center" prop="max" />
        <el-table-column label="最小值" align="center" prop="min" />
        <el-table-column label="平均数" align="center" prop="average" />
        <el-table-column label="总共数量" align="center" prop="total" />
        <el-table-column label="正常数量" align="center" prop="normal" />
        <el-table-column label="异常数量" align="center" prop="exception" />
        <el-table-column label="统计开始时间" align="center" prop="countBeginDate" />
        <el-table-column label="统计结束时间" align="center" prop="countEndDate" />
      </el-table>
      <span v-if="showSubmit" slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-refresh-right" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" size="small" @click="showSaveDialog()">保存</el-button>
      </span>
    </el-dialog>

    <!-- 弹出框 -->
    <el-dialog title="保存信息" :visible.sync="showSaveDialogVisible" width="40%">
      <el-form ref="dataForm" :model="statisticsData" label-width="100px" size="small" style="padding-right: 40px;">
        <el-form-item label="统计编码">
          <el-input v-model="statisticsData.code" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-refresh-right" @click="showSaveDialogVisible = false">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" size="small" @click="addStatistics()">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import api from '@/api/hardware/data/statistics'
import dataTypeRangeApi from '@/api/hardware/data/dataTypeRange'

export default {
  name: 'Statistics',
  data() {
    return {
      loading: true,
      dataList: [], // 表格数据
      statistics: {}, // 设备对象
      total: 0, // 总记录数
      queryParams: {
        current: 1, // 页码
        pageSize: 20, // 每页记录数
        code: ''
      },
      rangeTime: [],
      // 多选
      multipleSelection: [],
      dialogVisible: false,
      dialogTitle: '',

      dataTypeList: [],
      showSubmit: false,
      statisticsData: {},
      addDataList: [],
      showSaveDialogVisible: false
    }
  },
  beforeMount() {
    this.getDataTypeList()
    this.getListByPage()
  },
  methods: {

    showSaveDialog() {
      this.showSaveDialogVisible = true
    },

    async getStatisticsData() {
      if (this.statistics.dataType === null || this.rangeTime === null || this.rangeTime.length !== 2) {
        this.$message.error('请选择全部统计参数！')
        return
      }
      this.statistics.countBeginDate = this.rangeTime[0]
      this.statistics.countEndDate = this.rangeTime[1]
      this.addDataList = []
      const res = await api.getStatisticsData(this.statistics)
      this.statisticsData = res.data
      this.addDataList.push(res.data)
      this.$message.success('恭喜，统计数据成功！')
      this.showSubmit = true
    },

    /**
     * 获取数据类型
     *
     * @returns {Promise<void>}
     */
    async getDataTypeList() {
      const res = await dataTypeRangeApi.listDataTypeRange()
      this.dataTypeList = res.data
    },

    /**
     * 弹出添加的表单
     */
    showAdd() {
      this.dialogTitle = '添加统计数据'
      this.dialogVisible = true
      this.statistics = {}
      this.statisticsData = {}
      this.addDataList = []
      this.rangeTime = []
      this.showSubmit = false
    },

    /**
     * 创建设备
     */
    async addStatistics() {
      try {
        console.log(this.statisticsData)
        this.loading = true
        const res = await api.addStatistics(this.statisticsData)
        this.$message.success(res.message || '恭喜，添加操作成功！')
        this.dialogVisible = false
        this.showSaveDialogVisible = false
        await this.getListByPage(this.queryParams.current)
      } finally {
        this.loading = false
      }
    },

    // 当多选选项发生变化的时候调用
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },

    /**
     * 批量删除
     */
    batchDeleteStatistics() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const idList = []
        this.multipleSelection.forEach(statistics => { idList.push(statistics.id) })
        const res = await api.batchDeleteStatistics(idList)
        // TODO 是否要跳到当前页
        await this.getListByPage(this.queryParams.current)
        this.$message.success(res.message || '恭喜，批量删除操作成功！')
      }).catch()
    },

    /**
     * 重置查询表单
     */
    resetData() {
      this.queryParams.code = null
      this.getListByPage()
    },

    /**
     * 每页大小发生变化的回调
     *
     * @param pageSize
     */
    handleSizeChange(size) {
      console.log(this.queryParams.pageSize)
      this.queryParams.pageSize = size
      this.getListByPage()
    },

    /**
     * 分页查询
     *
     * @returns {Promise<void>}
     */
    async getListByPage(pageNum = 1) {
      try {
        this.queryParams.current = pageNum
        const res = await api.listStatisticsByPage(this.queryParams)
        this.dataList = res.data.records
        this.total = res.data.total
        this.queryParams.current = res.data.current
        this.queryParams.pageSize = res.data.size
      } finally {
        this.loading = false
      }
    }

  }

}
</script>

<style scoped>

</style>

